import re
import os

from PySide6.QtCore import Qt,QEvent
from PySide6.QtGui import QPixmap, QColor
from PySide6.QtWidgets import QWidget,QHBoxLayout, QVBoxLayout, QGridLayout, QLabel, QFrame, QPushButton, QSpacerItem, QSizePolicy,QStackedLayout
from qfluentwidgets import SubtitleLabel, PushButton, PrimaryPushButton, TitleLabel, CardWidget

from app.Dialog.dialog_attribute import DialogAttribute
from app.Dialog.dialog_find import DialogFind
from app.show_pet_info  import show_pet

# region 信息展示部件
class PetInfoWidget(CardWidget):
    """单个宠物信息展示部件"""
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setFixedHeight(190)
        
        # 主布局：图片在左，信息在右
        main_layout = QHBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        
        # 左侧图片区域
        self.image_label = QLabel(self)
        self.image_label.setFixedSize(200, 200)
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setScaledContents(True)
        self.image_label.setText("No Image")
        main_layout.addWidget(self.image_label)
        
        # 右侧信息区域（网格布局）
        info_widget = QFrame(self)
        grid_layout = QGridLayout(info_widget)
        grid_layout.setContentsMargins(5, 0, 5, 0)
        
        # 名字标签（跨两列）
        self.name_label = TitleLabel("", self)
        grid_layout.addWidget(self.name_label, 0, 0, 1, 2)
        
        # 编号标签
        grid_layout.addWidget(SubtitleLabel("编号:"), 1, 0)
        self.id_label = SubtitleLabel("", self)
        grid_layout.addWidget(self.id_label, 1, 1)
        
        # 血脉标签
        grid_layout.addWidget(SubtitleLabel("血脉:"), 2, 0)
        self.bloodline_label = SubtitleLabel("", self)
        grid_layout.addWidget(self.bloodline_label, 2, 1)
        
        # 属性标签
        grid_layout.addWidget(SubtitleLabel("属性:"), 3, 0)
        
        # 创建属性容器，使用水平布局放置两个属性标签
        self.attr_container = QWidget(self)
        attr_layout = QHBoxLayout(self.attr_container)
        attr_layout.setContentsMargins(0, 0, 0, 0)
        attr_layout.setSpacing(5)
        
        self.attr1_label = SubtitleLabel("", self.attr_container)
        self.attr1_label.setObjectName("attr1_label")
        self.attr1_label.setFixedSize(60, 30)
        self.attr1_label.setAlignment(Qt.AlignCenter)
        self.attr1_label.setStyleSheet("border-radius: 5px;")
        
        self.attr2_label = SubtitleLabel("", self.attr_container)
        self.attr2_label.setObjectName("attr2_label")
        self.attr2_label.setFixedSize(60, 30)
        self.attr2_label.setAlignment(Qt.AlignCenter)
        self.attr2_label.setStyleSheet("border-radius: 5px;")
        
        attr_layout.addWidget(self.attr1_label)
        attr_layout.addWidget(self.attr2_label)
        
        grid_layout.addWidget(self.attr_container, 3, 1)
        
        main_layout.addWidget(info_widget, 1)
        
    # region 外部调用
    def clear_data(self):
        """清空所有数据"""
        self.name_label.setText("")
        self.id_label.setText("")
        self.bloodline_label.setText("")
        self.attr1_label.setText("")
        self.attr2_label.setText("")
        self.image_label.setText(" ")
        self.attr1_label.setStyleSheet("")
        self.attr2_label.setStyleSheet("")
    
    def set_data(self, pet_data):
        """设置宠物数据"""
        # 设置基本数据
        self.name_label.setText(pet_data.get('name', ''))
        self.id_label.setText(str(pet_data.get('id', '')))
        self.bloodline_label.setText(pet_data.get('blood_line', ''))
            
        self.attr1_label.setText(pet_data.get('attribute_main', ''))
        self.attr2_label.setText(pet_data.get('attribute_sub', ''))
        
        # 加载图片
        image_path = f"pet_img/{pet_data.get('id', '')}.png"
        if os.path.exists(image_path):
            pixmap = QPixmap(image_path)
            if not pixmap.isNull():
                scaled_pixmap = pixmap.scaled(
                    100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation
                )
                self.image_label.setPixmap(scaled_pixmap)
            else:
                self.image_label.setText("Invalid Image")
        else:
            self.image_label.setText("No Image")
            
        # 刷新属性颜色
        self.refresh_attribute_color()
    
    def refresh_attribute_color(self):
        """刷新属性标签的颜色"""
        attribute_map = {
            "草系": "grass",
            "火系": "fire",
            "水系": "water",
            "光系": "light",
            "土系": "earth",
            "石系": "stone",
            "冰系": "ice",
            "龙系": "dragon",
            "电系": "electric",
            "毒系": "poison",
            "虫系": "bug",
            "武系": "fighting",
            "翼系": "flying",
            "萌系": "cute",
            "幽灵系": "ghost",
            "恶魔系": "demon",
            "机械系": "mechanical",
            "普通系": "normal",
            "神火系": "god_fire",
            "神草系": "god_grass",
            "神水系": "god_water",
            "无": "none"
        }
        self.set_attribute_color(self.attr1_label, attribute_map)
        self.set_attribute_color(self.attr2_label, attribute_map)
    
    def set_attribute_color(self, label, attribute_map):
        """设置单个属性标签的颜色 - 复用已有类选择器"""
        text = label.text().strip()
        if not text:
            # 清除样式
            label.setProperty("class", "")
            label.setStyleSheet("")
            return
            
        # 获取对应的类名
        class_name = attribute_map.get(text, "none")
        
        # 设置类属性
        label.setProperty("class", class_name)
        
        # 强制更新样式 - 重用QSS中已有的样式规则
        label.style().unpolish(label)
        label.style().polish(label)
        label.update()
# endregion


class PetShowWidget(QFrame):
    """宠物展示主部件"""
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.db = self.parent().db

        self.name = None
        self.id = None
        self.attribute = None
        self.now_id = 0
        self.search_stack = []
        self.current_pet_id = None

        self.setObjectName("PetShowWidget")
        self.setup_ui()
        self.setMinimumSize(700, 900)
        # 模拟初始化数据
        self.init_sample_data()
        self.installEventFilter(self)

# region ui  初始化
    def setup_ui(self):
        """设置UI布局 - 使用堆叠布局管理多个视图"""
        # 主堆叠布局
        self.stacked_layout = QStackedLayout(self)
        
        # 创建三个页面
        self.list_page = self.create_list_page()       # 宠物列表页
        self.attribute_page = self.create_attribute_page()  # 属性选择页
        self.detail_page = self.create_detail_page()   # 宠物详情页
        
        # 添加到堆叠布局
        self.stacked_layout.addWidget(self.list_page)       # 索引0
        self.stacked_layout.addWidget(self.attribute_page)  # 索引1
        self.stacked_layout.addWidget(self.detail_page)     # 索引2
        
        # 默认显示列表页
        self.stacked_layout.setCurrentIndex(0)
        
        # 设置样式
        self.setStyleSheet("""
            PetShowWidget {
                background-color: white;
                border-radius: 8px;
            }
            QLabel {
                color: #333333;
            }
            #attr1_label, #attr2_label {
                font-size: 12px;
            }
        """)
        
        self.connect_init()
    
    def create_list_page(self):
        """创建宠物列表页面"""
        page = QWidget()
        layout = QVBoxLayout(page)
        layout.setContentsMargins(20, 15, 20, 15)
        layout.setSpacing(5)

        # 顶部控制栏
        top_layout = QHBoxLayout()
        top_layout.setSpacing(15) 

        self.search_btn = PrimaryPushButton("搜索", page)
        self.search_btn.setMinimumSize(100,48)

        self.title_label = TitleLabel("洛克王国", page)
        self.title_label.setAlignment(Qt.AlignCenter)

        self.attr_btn = PrimaryPushButton("属性", page)
        self.attr_btn.setMinimumSize(100,48)
        # self.attr_btn.setFixedHeight(36)
        
        top_layout.addWidget(self.search_btn)
        top_layout.addStretch(1)
        top_layout.addWidget(self.title_label)
        top_layout.addStretch(1)
        top_layout.addWidget(self.attr_btn)
        layout.addLayout(top_layout)
        
        # 中间的宠物展示网格 (2列x4行)
        self.grid_layout = QGridLayout()
        self.grid_layout.setHorizontalSpacing(20)
        self.grid_layout.setVerticalSpacing(10)
        
        # 创建8个宠物信息小部件占位
        self.pet_widgets = []
        for i in range(8):
            row = i // 2
            col = i % 2
            pet_widget = PetInfoWidget()
            self.pet_widgets.append(pet_widget)
            self.grid_layout.addWidget(pet_widget, row, col)
        
        layout.addLayout(self.grid_layout, 1)  # 添加伸缩因子让这部分占据更多空间
        
        # 底部翻页控制
        bottom_layout = QHBoxLayout()

        self.prev_btn = PushButton("上一页", page)
        self.prev_btn.setMinimumSize(100,48)
        
        self.next_btn = PushButton("下一页", page)
        self.next_btn.setMinimumSize(100,48)
        
        bottom_layout.addWidget(self.prev_btn)
        bottom_layout.addStretch(1)  # 添加弹簧
        bottom_layout.addWidget(self.next_btn)
        layout.addLayout(bottom_layout)
        
        # 安装事件过滤器
        for widget in self.pet_widgets:
            widget.installEventFilter(self)
            widget.setAttribute(Qt.WA_StyledBackground)
        
        return page
    
    def create_attribute_page(self):
        """创建属性选择页面"""
        page = QWidget()
        layout = QVBoxLayout(page)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 返回按钮
        back_btn = PushButton("返回列表", page)
        back_btn.setFixedSize(120, 60)
        back_btn.clicked.connect(lambda: self.stacked_layout.setCurrentIndex(0))
        layout.addWidget(back_btn, alignment=Qt.AlignLeft)
        
        # 添加属性选择对话框
        self.attribute_dialog = DialogAttribute(parent=self)
        layout.addWidget(self.attribute_dialog)  # 添加伸缩因子
        self.attribute_dialog.Signal_attribute.connect(self.on_attribute_selected)
        return page
    
    def create_detail_page(self):
        """创建宠物详情页面"""
        page = QWidget()
        layout = QVBoxLayout(page)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 返回按钮
        back_btn = PushButton("返回列表", page)
        back_btn.setFixedSize(120, 60)
        back_btn.clicked.connect(lambda: self.stacked_layout.setCurrentIndex(0))
        layout.addWidget(back_btn, alignment=Qt.AlignLeft)
        
        # 通过UI文件加载宠物详情部件
        self.pet_detail = show_pet(parent=self)
        layout.addWidget(self.pet_detail)
        
        return page
# endregion

# region 显示具体宠物
    def eventFilter(self, source, event):
        """事件过滤器处理点击事件"""
        if event.type() == QEvent.MouseButtonPress and event.button() == Qt.LeftButton:
            if source in self.pet_widgets:
                index = self.pet_widgets.index(source)
                self.handle_widget_click(index)
                return True
        return super().eventFilter(source, event)

    def handle_widget_click(self, index):
        """处理部件点击"""
        if 0 <= index < len(self.pet_widgets):
            self.on_widget_clicked(index)

    def on_widget_clicked(self, index):
        """显示宠物详细信息（堆叠布局模式）"""
        pet_id = self.pet_widgets[index].id_label.text()
        if not pet_id:
            return
        
        # 设置当前宠物ID
        self.current_pet_id = pet_id
        
        # 更新详情页内容
        self.pet_detail.set_pet_id(pet_id)
        
        # 切换到详情页
        self.stacked_layout.setCurrentIndex(2)
# endregion

    def on_pet_detail_closed(self, window):
        """当宠物详情窗口关闭时执行清理"""
        if window in self.pet_detail_windows:
            self.pet_detail_windows.remove(window)
# endregion
# region 初始化数据
    def init_sample_data(self):
        """初始化示例数据"""
        pet_data_list=self.get_pets_data()
        self.update_pets(pet_data_list)
    
# endregion

# region 信号槽
    def connect_init(self):
        self.next_btn.clicked.connect(self.next_pet)
        self.prev_btn.clicked.connect(self.last_pet)
        self.attr_btn.clicked.connect(self.select_attribute)
        self.search_btn.clicked.connect(self.find_pet)


    def next_pet(self):
        """
         下一页
        """
        if self.pet_widgets[7].id_label.text() == "":
            return
        self.search_stack.append(self.now_id)
        self.now_id = int(self.pet_widgets[7].id_label.text())+1
        self.show_pet_info()

    def last_pet(self):
        """
         上一页
        """
        if len(self.search_stack) == 0:
            return
        self.now_id = self.search_stack.pop()
        self.show_pet_info()
    def select_attribute(self):
        """
         选择属性
        """
        self.stacked_layout.setCurrentIndex(1)

    
    def find_pet(self):
        """
            找名字或者id
        """
        dialog=DialogFind(self)

        dialog.Signal_find.connect(self.on_find_selected)
        dialog.exec()
# endregion

# region dialog回调函数
    def on_attribute_selected(self,attribute):
        """
        接收选择的属性
        """
        if not attribute == "取消": 
            self.clear_limit()
    
            if not attribute == "清空":
                self.attribute = attribute
        
        # self.show()
        self.stacked_layout.setCurrentIndex(0)
        self.show_pet_info()

    
    def on_find_selected(self,get_string):
        """
        接收选择的名字或者id
        """
        if  not get_string == "取消":
            self.clear_limit()
            if get_string.isdigit():
                self.id = int(get_string)
            else:
                self.name = get_string  

        self.show_pet_info()
# endregion

# region 宠物数据
    def clear_limit(self):
        """
        清空限制条件
        """
        self.search_stack.clear()
        self.attribute = None
        self.name = None
        self.id = None
        self.now_id = 0
    
    def show_pet_info(self):
        """
        显示当前宠物信息
        """

        pet_data_list=self.get_pets_data()
        if len(pet_data_list) == 0:
            return
        self.update_pets(pet_data_list)
    def get_pets_data(self):
        """获取宠物数据"""
        return self.db.search_pets(id=self.id,name=self.name, attribute=self.attribute, now_id=self.now_id)

    def extract_pet_data(self,pet_tuple):
        """
        将原始宠物数据元组转换为结构化字典
        参数: 
            pet_tuple (tuple) - (name, id, blood_line, attribute_str, ...)
        返回: 
            dict - 包含结构化字段的字典
        """
        # 定义字段映射关系（元组索引 -> 字段名）
        FIELD_MAPPING = {
            0: 'name',
            1: 'id',
            2: 'blood_line',
            3: 'attribute'  # 原始属性字段
        }
        
        # 初始化基础字段
        data = {
            FIELD_MAPPING[i]: value 
            for i, value in enumerate(pet_tuple) 
            if i in FIELD_MAPPING
        }
        
        # 处理属性字段
        attr_str = data.get('attribute', '')
        attributes = re.split(r'[、>]', attr_str)
        
        # 解构主/副属性
        data['attribute_main'] = attributes[0] if attributes else ''
        data['attribute_sub'] = attributes[1] if len(attributes) > 1 else ''
        
        # 移除原始未处理的属性字段
        data.pop('attribute', None)
        
        return data
    def update_pets(self, pet_data_list):
        """更新显示宠物数据"""
        # 先清除所有宠物信息
        for widget in self.pet_widgets:
            widget.clear_data()
        
        # 设置新的宠物数据
        for i, pet_data in enumerate(pet_data_list[:8]):
            data_info=self.extract_pet_data(pet_data)
            self.pet_widgets[i].set_data(data_info)
# endregion